<?php

namespace app\admin\controller\sum\trade;

use addons\sum\library\Export;
use app\admin\controller\sum\Base;
use app\admin\model\sum\trade\Order as TradeOrderModel;
use think\Db;

class Order extends Base
{

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new TradeOrderModel();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $nobuildfields = ['user_nickname', 'user_mobile'];
            list($where, $sort, $order, $offset, $limit) = $this->custombuildparams(null, $nobuildfields);

            $total = $this->buildSearch()
                ->where($where)
                ->where('status','in',['paid','refund'])
                ->order($sort, $order)
                ->count();

            $list = $this->buildSearch()
                ->with('user')
                ->where($where)
                ->where('status','in',['paid','refund'])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return $this->success('操作成功', null, $result);
        }
        return $this->view->fetch();
    }

    /**
     * 提现搜索
     *
     * @return object
     */
    public function buildSearch()
    {
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter = $filter ? $filter : [];

        $user_nickname = isset($filter['user_nickname']) ? $filter['user_nickname'] : '';
        $user_mobile = isset($filter['user_mobile']) ? $filter['user_mobile'] : '';

        // 当前表名
        $tableName = $this->model->getQuery()->getTable();

        $applys = $this->model;

        // 购买人查询
        if ($user_nickname || $user_mobile) {
            $applys = $applys->whereExists(function ($query) use ($user_nickname, $user_mobile, $tableName) {
                $userTableName = (new \app\admin\model\User())->getQuery()->getTable();
                $query = $query->table($userTableName)->where($userTableName . '.id=' . $tableName . '.user_id');

                if ($user_nickname) {
                    $query = $query->where('nickname', 'like', "%{$user_nickname}%");
                }

                if ($user_mobile) {
                    $query = $query->where('mobile', 'like', "%{$user_mobile}%");
                }

                return $query;
            });
        }

        return $applys;
    }

    /**
     * 订单导出
     */
    public function export()
    {
        $nobuildfields = ['user_nickname', 'user_mobile'];
        list($where, $sort, $order, $offset, $limit) = $this->custombuildparams(null, $nobuildfields);

        $expCellName = [
            'id' => 'ID',
            'user_phone' => '充值用户',
            'createtime_text' => '充值时间',
            'order_amount' => '充值金额',
            'pay_fee' => '支付金额',

        ];
        $export = new Export();
        $spreadsheet = null;
        $sheet = null;

        $total = $this->buildSearch()
            ->where($where)
            ->where('status','in',['paid','refund'])
            ->order($sort, $order)
            ->count();

        $current_total = 0;     // 当前已循环条数
        $page_size = 2000;
        $total_page = intval(ceil($total / $page_size));
        if ($total == 0) {
            $this->error('导出数据为空');
        }
        for ($i = 0; $i < $total_page; $i++) {
            $page = $i + 1;
            $is_last_page = ($page == $total_page) ? true : false;
            $list = $this->buildSearch()
                ->with('user')
                ->where($where)
                ->where('status','in',['paid','refund'])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $item){
                $item['user_phone']= $item['user'] ? $item['user']['mobile'] . ' ' : '';
                $item['createtime_text']= date("Y-m-d H:i:s",$item['createtime']);
            }

            $list = collection($list)->toArray();
            $current_total += count($list);     // 当前循环总条数
            $export->exportExcel('充值订单列表-' . date('Y-m-d H:i:s'), $expCellName, $list, $spreadsheet, $sheet, [
                'page' => $page,
                'current_total' => $current_total,
                'is_last_page' => $is_last_page
            ]);
        }
    }

    /**
     * 退款
     * @param $ids
     * @return void
     */
    public function refund($ids)
    {
        if ($this->request->isAjax()) {
            $refund_money = round($this->request->post('refund_money', 0), 2);

            if ($refund_money < 0) {
                $this->error('退款金额不能小于 0');
            }
            $order=$this->model->where('status','paid')->where('id',$ids)->find();

            if (!$order) {
                $this->error('订单不存在或不可退款');
            }
            // 当前订单已退款总金额
            $refunded_money = $order['refund_fee'];
            // 剩余可退款金额
            $refund_surplus_money = $order->pay_fee - $refunded_money;
            // 如果退款金额大于订单支付总金额
            if ($refund_money > $refund_surplus_money) {
                $this->error('退款总金额不能大于实际支付金额');
            }
            try {
                Db::transaction(function () use ($order, $refund_money, $refund_surplus_money) {
                    \app\admin\model\sum\trade\Order::startRefund($order, $refund_money, $this->auth->getUserInfo(), '管理员操作退款');
                });
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('操作成功');
        }
    }

}
